package imageCleanup;
import preproc.Image;
import utils.Constants;


public class CleanupFilter {
	
	
	// dark regions become smaller
	public void erode(Image image) {
		int w = image.getWidth();
		int h = image.getHeight();
		int[][] I = image.intensity;
		int[][] auxI = new int[h][w];
		int sz = Constants.TEMPLATE_SIZE;
		for (int r=0; r<h; r++) {
			for (int c=0; c<w; c++) {
				int maxI = -1;
				int minR = Math.max(r-sz, 0);
				int maxR = Math.min(r+sz, h-1);
				int minW = Math.max(c-sz, 0);
				int maxW = Math.min(c+sz, w-1);
				for (int r0=minR; r0<=maxR; r0++) {
					for (int c0=minW; c0<=maxW; c0++) {
						if (I[r0][c0] > maxI) {
							maxI = I[r0][c0];
						}
					}
				}
				auxI[r][c] = maxI;
			}
		}
		for (int r=0; r<h; r++) {
			for (int c=0; c<w; c++) {
				I[r][c] = auxI[r][c]; 
			}
		}
	}
	
	// dark regions are extended
	public void dilate(Image image) {
		int w = image.getWidth();
		int h = image.getHeight();
		int[][] I = image.intensity;
		int[][] auxI = new int[h][w];
		int sz = Constants.TEMPLATE_SIZE;
		for (int r=0; r<h; r++) {
			for (int c=0; c<w; c++) {
				int minI = 1000;
				int minR = Math.max(r-sz, 0);
				int maxR = Math.min(r+sz, h-1);
				int minW = Math.max(c-sz, 0);
				int maxW = Math.min(c+sz, w-1);
				for (int r0=minR; r0<=maxR; r0++) {
					for (int c0=minW; c0<=maxW; c0++) {
						if (I[r0][c0] < minI) {
							minI = I[r0][c0];
						}
					}
				}
				auxI[r][c] = minI;
			}
		}
		for (int r=0; r<h; r++) {
			for (int c=0; c<w; c++) {
				I[r][c] = auxI[r][c];
			}
		}
	}
	
	public void threshold(Image image) {
		int w = image.getWidth();
		int h = image.getHeight();
		int[][] I = image.intensity;
		
		for (int r=0; r<h; r++) {
			for (int c=0; c<w; c++) {
				if (I[r][c] < Constants.THRESHOLD)
					I[r][c] = 0;
				else 
					I[r][c] = 255;
			}
		}
	}
	
	
	public void cleanImage(Image img) {

		
		for (int i=0; i<Constants.NUM_DILATIONS; i++)
			dilate(img);
		
		for (int i=0; i<Constants.NUM_EROSIONS; i++)
			erode(img);
		
		threshold(img);


	}
}
